import { ref } from "vue";
import { defineStore } from "pinia";

/**
 * 登录用户信息
 */
export const useLoginInfoStore = defineStore("loginInfoStore", () => {
  const LOGIN_INFO = ref<any>({});

  let syncLoginInfoPromise: Promise<void> | null = null;

  /**
   * 同步登录用户信息
   */
  async function syncLoginInfo() {
    try {
      if (syncLoginInfoPromise) {
        await syncLoginInfoPromise;
      } else {
        syncLoginInfoPromise = (async function () {
          await uni.showLoading({ title: "正在验证登录..." });
          //todo 调用接口获取用户信息
          LOGIN_INFO.value = {
            id: "1",
            loginName: "admin",
            name: "管理员",
            phone: "18888888888",
            email: "admin@admin.com",
          };
        })();
        try {
          await syncLoginInfoPromise;
        } finally {
          syncLoginInfoPromise = null;
        }
      }
    } catch (e) {
      console.warn("登录失败", e);
      throw e;
    } finally {
      uni.hideLoading();
    }
  }

  async function logout() {
    // 清除权限等其他信息
    LOGIN_INFO.value = {};
    uni.setStorageSync("ticket", "");
  }

  return {
    LOGIN_INFO,
    syncLoginInfo,
    logout,
  };
});
